package com.xiaohao;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

import java.io.File;

/**
 * Created by huanhuan on 2017/8/19.
 */
@Mojo(name = "countJavaFile", defaultPhase = LifecyclePhase.PACKAGE)
public class CountJavaFilePlugin extends AbstractMojo {

    /**
     * 项目路径
     */
    @Parameter(defaultValue = "${user.dir}", property = "uri")
    private String uri;

    /**
     * 要统计的文件类型
     */
    private String type = ".java";

    public void execute() throws MojoExecutionException, MojoFailureException {
        getLog().info("==========statistic begin==========");
        getLog().info(String.format("parameters[uri:%s, type:%s]", uri, type));

        try { 
            File file = new File(uri);
            int num = countFile(file);
            getLog().info(String.format("总共有%s个java文件", num));
        } catch (Exception e) {
            getLog().info("统计出错", e);
        }

        getLog().info("==========statistic end==========");
    }

    /**
     * 统计java文件数
     * @param targetFile
     * @return
     */
    private int countFile(File targetFile) {

        int num = 0;

        for (File file : targetFile.listFiles()) {

            if (file.isFile() && file.getName().endsWith(type)) {
                num ++;
            } else if (file.isDirectory()) {
                num += countFile(file);
            }

        }
        return num;
    }

}
